#!/usr/bin/env python3
"""
自动修复支付宝配置脚本
1. 自动检测ngrok地址
2. 更新.env文件配置
3. 验证配置是否正确
"""
import os
import json
import requests
from pathlib import Path
from loguru import logger

def get_ngrok_url():
    """从ngrok API获取公网地址"""
    try:
        # ngrok本地API地址
        response = requests.get("http://127.0.0.1:4040/api/tunnels", timeout=2)
        if response.status_code == 200:
            data = response.json()
            tunnels = data.get("tunnels", [])
            for tunnel in tunnels:
                public_url = tunnel.get("public_url", "")
                if public_url.startswith("https://"):
                    return public_url
    except Exception as e:
        logger.warning(f"无法从ngrok API获取地址: {e}")
    return None

def update_env_file(ngrok_url=None):
    """更新.env文件"""
    base_dir = Path(__file__).parent
    env_file = base_dir / '.env'
    
    print("=" * 80)
    print("支付宝配置修复工具")
    print("=" * 80)
    
    # 尝试自动获取ngrok地址
    if not ngrok_url:
        print("\n正在尝试自动检测ngrok地址...")
        ngrok_url = get_ngrok_url()
    
    if ngrok_url:
        print(f"✅ 检测到ngrok地址: {ngrok_url}")
    else:
        print("\n⚠️  无法自动检测ngrok地址")
        print("请确保：")
        print("1. ngrok正在运行（ngrok http 8000）")
        print("2. ngrok Web界面可访问（http://127.0.0.1:4040）")
        print("\n或者手动输入ngrok地址：")
        ngrok_url = input("请输入ngrok地址（例如：https://abc123.ngrok-free.dev）: ").strip()
        if not ngrok_url:
            print("❌ 未输入地址，退出")
            return False
    
    # 清理输入
    ngrok_url = ngrok_url.replace('http://', '').replace('https://', '').replace('/', '')
    ngrok_url = f"https://{ngrok_url}"
    
    # 读取现有配置
    existing_config = {}
    env_lines = []
    
    if env_file.exists():
        with open(env_file, 'r', encoding='utf-8') as f:
            env_lines = f.readlines()
            for line in env_lines:
                line = line.strip()
                if '=' in line and not line.startswith('#'):
                    key, value = line.split('=', 1)
                    existing_config[key.strip()] = value.strip()
    
    # 准备更新的配置
    notify_url = f"{ngrok_url}/api/payment/alipay/notify"
    return_url = f"{ngrok_url}/api/payment/alipay/return"
    
    # 从错误URL中看到的APP_ID是9021000157661754，优先使用环境变量中的值
    config_updates = {
        'ALIPAY_APP_ID': existing_config.get('ALIPAY_APP_ID', os.getenv('ALIPAY_APP_ID', '9021000157661754')),
        'ALIPAY_NOTIFY_URL': notify_url,
        'ALIPAY_RETURN_URL': return_url,
        'ALIPAY_DEBUG': existing_config.get('ALIPAY_DEBUG', os.getenv('ALIPAY_DEBUG', 'True')),
    }
    
    # 显示配置预览
    print("\n" + "=" * 80)
    print("配置预览：")
    print("=" * 80)
    for key, value in config_updates.items():
        print(f"{key} = {value}")
    print("=" * 80)
    
    # 更新配置
    updated_lines = []
    updated_keys = set()
    
    for line in env_lines:
        stripped = line.strip()
        if '=' in stripped and not stripped.startswith('#'):
            key = stripped.split('=', 1)[0].strip()
            if key in config_updates:
                updated_lines.append(f"{key}={config_updates[key]}\n")
                updated_keys.add(key)
                continue
        updated_lines.append(line)
    
    # 添加未存在的配置
    for key, value in config_updates.items():
        if key not in updated_keys:
            updated_lines.append(f"{key}={value}\n")
    
    # 确保有必要的其他配置
    required_configs = {
        'MYSQL_HOST': 'localhost',
        'MYSQL_PORT': '3306',
        'MYSQL_USER': 'root',
        'MYSQL_PASSWORD': '123456',
        'MYSQL_DATABASE': 'xiang',
        'REDIS_HOST': 'localhost',
        'REDIS_PORT': '6379',
        'REDIS_DB': '0',
        'JWT_SECRET_KEY': 'your-secret-key-change-in-production',
    }
    
    existing_keys = {line.split('=', 1)[0].strip() for line in updated_lines 
                     if '=' in line.strip() and not line.strip().startswith('#')}
    
    for key, default_value in required_configs.items():
        if key not in existing_keys:
            updated_lines.append(f"{key}={default_value}\n")
    
    # 写入文件
    with open(env_file, 'w', encoding='utf-8') as f:
        f.writelines(updated_lines)
    
    print(f"\n✅ 配置已保存到: {env_file}")
    print("\n下一步：")
    print("1. 确保后端服务在8000端口运行")
    print("2. 确保ngrok正在运行并转发到8000端口")
    print("3. 重启后端服务以加载新配置")
    print("4. 测试支付功能")
    
    return True

if __name__ == '__main__':
    try:
        update_env_file()
    except KeyboardInterrupt:
        print("\n\n已取消")
    except Exception as e:
        print(f"\n❌ 错误: {e}")
        import traceback
        traceback.print_exc()

